package lion.framework.core.db.datasource;

import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import lion.dev.exception.DBException;
import lion.dev.lang.MapJ;
import lion.framework.core.db.DataSourceManager;
import lion.framework.core.db.anno.DataSourceProvider;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * C3P0连接池提供者； 特殊配置:<br/>
 * 1、helpers: c3p0 helper thread的数量<br/>
 * 2、idletime:连接最大空闲时间，超出将被关闭,以节省资源,默认5分钟
 *
 * <pre>
 * time   2013年8月6日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@DataSourceProvider("c3p0")
public class C3P0DataSourceProvider implements IDataSourceProvider {

	private MapJ config;

	public C3P0DataSourceProvider(MapJ config) {

		this.config = config;
	}

	@Override
	public DataSource getDataSource() {

		ComboPooledDataSource cpds = new ComboPooledDataSource();
		try {
			cpds.setDriverClass(DataSourceManager.getJDBCDriver(config.getString("type")));
		} catch (PropertyVetoException e) {
			throw new DBException("driver class not found", e);
		}
		cpds.setJdbcUrl(String.format(DataSourceManager.getDriverURLTemplate(config.getString("type", "mysql")), config.getString("server", "localhost"),
				config.getInt("port", 3306), config.getString("db")));

		cpds.setUser(config.getString("user"));
		cpds.setPassword(config.getString("password"));
		cpds.setInitialPoolSize(config.getInt("init", 10));
		cpds.setMinPoolSize(config.getInt("init", 10));
		cpds.setMaxPoolSize(config.getInt("max", 100));
		cpds.setAcquireIncrement(config.getInt("init", 10));// 每次新获取数量

		cpds.setMaxIdleTime(config.getInt("idletime", 300000));// 最大空闲5分钟
		cpds.setIdleConnectionTestPeriod(1800);// 3分钟检查一次空闲
		//
		cpds.setNumHelperThreads(config.getInt("helpers", 3));//

		return cpds;
	}

}
